package com.huaqin.customer.expansion;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.huaqin.common.Util;
import com.huaqin.customer.ConditionInterface;
import com.huaqin.salestracker.SalesTrackerService;

/*
 * 通话相关条件类
 */
public class ConditionCall implements ConditionInterface{
	
	private static final String TAG = "ConditionCall";

	private static final String SINGLE_TIME = "SingleTalkTime";
	private static final String SINGLE_OUTGOING_TIME = "SingleOutgoingTime";
    private static final String SINGLE_INCOMING_TIME = "SingleIncomingTime";
	private static final String CUMULATIVE_TIME = "CumulativeTalkTime"; 
	private static final String CUMULATIVE_OUTGOING_TIME = "CumulativOutgoingTime";
    private static final String CUMULATIVE_INCOMING_TIME = "CumulativIncomingTime";	
	
	private static final String KEY_LAST_OUTGOING_TIME = "LastOutgoingTime";
	private static final String KEY_LAST_INCOMING_TIME = "LastIncomingTime";

	private String mKey;
	private String mOperator;
	private String mValues;
	private String mDialingPhoneNumber = null;
	
	TelephonyManager mTelephonyMgr = null;
	private static IncomingCallListener mIncomingCall = null;
	private static OutgoingCallReceiver mOutgoingCall = null;
	
	private long mCurrentTime = 0;
	private long mTimeInterval = 0;
	private static long mLastOutcomingTime = 0;
	private static long mLastIncomingTime = 0;
	private long mTalkTimeValues = 0;
	private Context mContext = null;
	
	private boolean mDialingMode = false;
	private boolean mResult = false;
	private boolean mExecute = false;
	private boolean mListener = false;
	
	@Override
	public void setParam(String key, String operator, String values) {
		// TODO Auto-generated method stub
		mKey = key;
		mOperator = operator;
		mValues = values;

		init();
	}

	/**
	 * 根据传入的参数执行当前条件
	 */
	@Override
	public boolean execute() {
		// TODO Auto-generated method stub
		Log.i(TAG, "==> execute()");
		if(!mExecute){
		    RegisterPhoneStateListener(true);
		    mExecute = true;
		}
		
		return mResult;
	}
	
	private void init(){
		mTalkTimeValues = Integer.parseInt(mValues) * 60 * 1000;
		
		mContext = SalesTrackerService.mContext;

		if(mKey.equals(CUMULATIVE_TIME)){
		    mLastOutcomingTime = Util.getLongPref(mContext, KEY_LAST_OUTGOING_TIME, 0);
		    mLastIncomingTime = Util.getLongPref(mContext, KEY_LAST_INCOMING_TIME, 0);
		}
	}
	
	@Override
	public void finish() {

		// TODO Auto-generated method stub
		RegisterPhoneStateListener(false);
	}

	@Override
	public boolean getResult() {
		// TODO Auto-generated method stub
		if(mOperator.equals(">")){
			mResult = (mTimeInterval > mTalkTimeValues);
		}
		else if(mOperator.equals(">=")){
			mResult = (mTimeInterval > mTalkTimeValues);
		}
		else if(mOperator.equals("==")){
			mResult = (mTimeInterval > mTalkTimeValues);
		}
		else if(mOperator.equals("<=")){
			mResult = (mTimeInterval > mTalkTimeValues);
		}
		else if(mOperator.equals("<")){
			mResult = (mTimeInterval > mTalkTimeValues);
		}
		else{
			Log.e("ConditionStandbyTime", "Unknown Operator:[" + mOperator + "]");
		}

		Log.i(TAG, "ConditionCall getResult:" + mResult + "(" + mTimeInterval +")") ;
		return mResult;
	}

	@Override
	public String getKeyDescription() {
		// TODO Auto-generated method stub
		if(mKey.equals(SINGLE_TIME)){
			
		}
		else if(mKey.equals(CUMULATIVE_TIME)){
			
		}
		
		return null;
	}
	
	private void checkCalled(){
	    if(getResult()){
	        Intent readyIntent = new Intent(SalesTrackerService.STCMD_SEND_AREADY);
	        mContext.sendBroadcast(readyIntent);
	        
	        Log.i(TAG, "ConditionCall Ready!");
	        RegisterPhoneStateListener(false);
	    }
	}
	
	private void RegisterPhoneStateListener(boolean register){
		
		Log.v(TAG, "RegisterPhoneStateListener register[" + register + "]");
		
		if(register){
			
			if(mIncomingCall == null){
				mIncomingCall = new IncomingCallListener();
			}
			
			if(mOutgoingCall == null){
				mOutgoingCall = new OutgoingCallReceiver();
			}
			
			//Incoming Call
		    mTelephonyMgr = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
			mTelephonyMgr.listen(mIncomingCall, PhoneStateListener.LISTEN_CALL_STATE);

			IntentFilter commandFilter = new IntentFilter();
			commandFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
			mContext.registerReceiver(mOutgoingCall, commandFilter);
		}
		else{

			if(mIncomingCall != null){
				mTelephonyMgr.listen(mIncomingCall, PhoneStateListener.LISTEN_NONE);
				mIncomingCall = null;
			}

			if(mOutgoingCall != null){
			    mContext.unregisterReceiver(mOutgoingCall);
			    mOutgoingCall = null;
			}
		}
	}
	
	class IncomingCallListener extends PhoneStateListener {

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			super.onCallStateChanged(state, incomingNumber);

			switch (state) {

				case TelephonyManager.CALL_STATE_IDLE: {
					Log.v(TAG, "CALL_STATE_IDLE");
					
					if(mListener){
					    long talkTimeInterval = System.currentTimeMillis() - mCurrentTime;
					    Log.d(TAG, mKey + " talk time interval:" + talkTimeInterval);
					    
	                    if(mKey.equals(SINGLE_TIME) || mKey.equals(SINGLE_OUTGOING_TIME) 
	                            || mKey.equals(SINGLE_INCOMING_TIME)){
	                        mTimeInterval = talkTimeInterval;
	                    }
	                    else if(mKey.equals(CUMULATIVE_TIME)){
	                        mTimeInterval = mTimeInterval + mLastIncomingTime + mLastOutcomingTime;
	                    }
	                    else if(mKey.equals(CUMULATIVE_OUTGOING_TIME)){
	                        mTimeInterval = mLastOutcomingTime + talkTimeInterval;
	                    }
	                    else if(mKey.equals(CUMULATIVE_INCOMING_TIME)){
	                        mTimeInterval = mLastOutcomingTime + talkTimeInterval;
	                    }
	                    
	                    if(mDialingMode){
                            Util.setLongPref(mContext, KEY_LAST_OUTGOING_TIME, talkTimeInterval);
                        }
                        else{
                            Util.setLongPref(mContext, KEY_LAST_INCOMING_TIME, talkTimeInterval);
                        }
	                    
	                    checkCalled();
					}
					
					mListener = false;
	
					break;
				}
				
				case TelephonyManager.CALL_STATE_OFFHOOK: {
					Log.v(TAG, "CALL_STATE_OFFHOOK mode: " + (mDialingMode ? "Outgoing" : "Incoming"));
					mListener = true;
				    mCurrentTime = System.currentTimeMillis();

					break;
				}
				
				// 来电状态，电话铃声响起的那段时间或正在通话又来新电，新来电话不得不等待的那段时间。
				case TelephonyManager.CALL_STATE_RINGING: {
					Log.v(TAG, "CALL_STATE_RINGING");

					break;
				}
				
				default:
					break;
			}
		}

	}
	
	public class OutgoingCallReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(intent != null && intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
				
			    mDialingMode = true;
			    mDialingPhoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
				
				Log.v(TAG, "Outgoing phone number:[" + mDialingPhoneNumber + "]");
			}
		}
		
	}
	
}
